package yong.hee;

import java.net.*;

import twitter4j.*;
import android.content.*;
import android.database.sqlite.*;
import android.provider.*;
import android.util.*;

public class DbHelper extends SQLiteOpenHelper {
	Context context;
	static final String TAG = "DbHelper";
	static final String DB_NAME = "timeline.db";
	static final int DB_VERSION = 3;
	static final String TABLE = "timeline";
	static final String C_ID = BaseColumns._ID;
	static final String C_CREATED_AT = "created_at";
	static final String C_TEXT_BODY = "twit_body";
	static final String C_SCREEN_NAME = "screen_name";
	static final String C_IMAGE_URL = "twit_image_url";
	
	
	
	static final String SQL_CREATE_TABLE = "CREATE TABLE timeline ("
		+ "_id INTEGER PRIMARY KEY," + "created_at INTEGER," + "friend_name TEXT,"
		+ "screen_name TEXT," + "twit_body TEXT," + "twit_image_url,"
		+ "geo_location_latitude INTEGER,"
		+ "geo_location_longitude INTEGER," + "follower_count INTEGER,"
		+ "url TEXT," + "location," + "retweet_id INTEGER" + ");";

	/** Constructor for DbHelper */
	public DbHelper(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
		this.context = context;
	}

	/** Called only once, first time database is created */
	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(SQL_CREATE_TABLE); // execute the sql
		Log.d(TAG, "onCreate'd sql: " + SQL_CREATE_TABLE);
	}

	/** Called every time DB version changes */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.d(TAG, String.format("onUpgrade from %s to %s", oldVersion,
				newVersion));
		// temporary
		db.execSQL("DROP TABLE IF EXISTS timeline;");
		this.onCreate(db);
	}


	/** Converts Twitter.Status to ContentValues */
	public static ContentValues statusToContentValues(Status status) {
		ContentValues ret = new ContentValues();
		ret.put(C_ID, status.getId());
		ret.put(C_CREATED_AT, status.getCreatedAt().getTime());
		ret.put(C_TEXT_BODY, status.getText());
		ret.put(C_SCREEN_NAME, status.getUser().getScreenName());

		User user = status.getUser();
		URL url = user.getProfileImageURL();
		GeoLocation gl = status.getGeoLocation();
		double latitude = 0;
		double longitude = 0;
		if (gl != null) {
			latitude = gl.getLatitude();
			longitude = gl.getLongitude();
		}
		ret.put("friend_name", user.getName());
		ret.put("twit_image_url", url.toString());
		if (gl != null) {
			ret.put("geo_location_latitude", latitude);
			ret.put("geo_location_longitude", longitude);
		}
		ret.put("follower_count", user.getFollowersCount());
		if (user.getURL() != null)
			ret.put("url", user.getURL().toString());
		if (user.getLocation() != null)
			ret.put("location", user.getLocation());
		if (status.getRetweetedStatus() != null) {
			ret.put("retweet_id", status.getRetweetedStatus().getId());
		}

		return ret;
	}

}
